package com.gph.saviorframework.wf.command;

import java.util.Iterator;
import java.util.Map;

import org.activiti.engine.impl.context.Context;
import org.activiti.engine.impl.interceptor.Command;
import org.activiti.engine.impl.interceptor.CommandContext;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.impl.persistence.entity.ExecutionEntityManager;
import org.activiti.engine.impl.persistence.entity.TaskEntity;
import org.activiti.engine.impl.pvm.process.ActivityImpl;

/**
 * 流程跳转命令
 * @author guopeihui
 *
 */
public class JumpTaskCmd implements Command<Void> {
	
	protected String executionId; 
	protected ActivityImpl desActivity; 
	protected Map<String, Object> paramvar; 
	protected ActivityImpl currentActivity;
	
	public JumpTaskCmd(String executionId, ActivityImpl desActivity, 
			Map<String, Object> paramvar, ActivityImpl currentActivity) { 
		this.executionId = executionId; 
		this.desActivity = desActivity; 
		this.paramvar = paramvar; 
		this.currentActivity = currentActivity; 
	}

	@Override
	public Void execute(CommandContext commandContext) {
		ExecutionEntityManager executionEntityManager = Context.getCommandContext().getExecutionEntityManager();
		// 获取当前流程的executionId，因为在并发的情况下executionId是唯一的。 
		ExecutionEntity executionEntity = executionEntityManager.findExecutionById(executionId); 
		executionEntity.setVariables(paramvar);
		// 根据executionId 获取Task 
		Iterator<TaskEntity> taskEntityIterator = Context.getCommandContext().getTaskEntityManager().findTasksByExecutionId(this.executionId).iterator();
		while (taskEntityIterator.hasNext()) {
			TaskEntity taskEntity = (TaskEntity) taskEntityIterator.next();
			taskEntity.setExecutionId(null);
			Context.getProcessEngineConfiguration().getTaskService().saveTask(taskEntity);
			/*// 触发任务监听
			taskEntity.fireEvent("complete");*/
			// 删除任务的原因
			Context.getProcessEngineConfiguration().getTaskService().deleteTask(taskEntity.getId(),true);
			//Context.getCommandContext().getTaskEntityManager().deleteTask(taskEntity, "completed", true);
		}
		executionEntity.setActivity(desActivity);
		executionEntity.executeActivity(this.desActivity); 
		return null; 
	}

}
